package cn.shangqizhenshuai.sqiot.Filter;


import com.google.gson.Gson;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@Order(1)
@WebFilter(filterName = "loginfilter", urlPatterns = "/*")
public class LoginFiter implements Filter {
    @Autowired
    UserLoginMap userLoginMap;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        request.setCharacterEncoding("UTF-8");
        StringBuffer pathInfo = request.getRequestURL();
        String parameter = request.getParameter("token");
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        ServletOutputStream out = servletResponse.getOutputStream();
        String requestURI = request.getRequestURI();
        String method = request.getMethod();

            //res.setContentType("application/json");
            servletResponse.setContentType("application/json; charset=utf-8");
            if (pathInfo.indexOf("login") == -1) {
                Gson gson = new Gson();
                HashMap<String, String> stringStringHashMap = new HashMap<>();
                if (parameter == null || parameter.equals("")) {
                    //10086 为无token
                    stringStringHashMap.put("errorcode", "10086");
                    String s = gson.toJson(stringStringHashMap);
                    out.print(s);
                } else {
                    if (userLoginMap.istokenexistence(parameter)) {
                        try {
                            filterChain.doFilter(servletRequest, servletResponse);
                        } catch (Exception e) {
                            //10089 为未知错误
                            stringStringHashMap.put("errorcode", "10089");
                            String s = gson.toJson(stringStringHashMap);
                            out.print(s);
                        }
                    } else {
                        //10087 为token过期
                        stringStringHashMap.put("errorcode", "10087");
                        String s = gson.toJson(stringStringHashMap);
                        out.print(s);
                    }
                }
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
            }

    }
    @Override
    public void destroy() {

    }
}
